package com.weitu.base.aop;

import com.weitu.permission.resource.service.ResourceService;
import com.weitu.permission.user.entity.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * @author LiMeng 2017/3/23
 */
public class ResourceInterceptor implements HandlerInterceptor {

    private final ResourceService resourceService;

    @Autowired
    public ResourceInterceptor(ResourceService resourceService) {
        this.resourceService = resourceService;
    }


    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        return true;
    }

    /**
     * 统一拦截list页面的方法 添加按钮权限
     *
     * @param httpServletRequest  request
     * @param httpServletResponse response
     * @param o                   o
     * @param modelAndView        modelAndView
     * @throws Exception exception
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        String resourceId = httpServletRequest.getParameter("resourceId");
        HttpSession session = httpServletRequest.getSession();
        User loginUser = (User) session.getAttribute("loginUser");
        String name = loginUser.getName();
        String deptId = loginUser.getDepartment().getId();
        if (StringUtils.isNotEmpty(resourceId)) {
            List<Map> buttonList = resourceService.selectAllButtonsByParentId(resourceId, name, deptId);
            httpServletRequest.setAttribute("buttonList", buttonList);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
